package com.gewu.pm.ui.activity.order;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.gewu.pm.R;
import com.gewu.pm.aop.SingleClick;
import com.gewu.pm.app.AppActivity;
import com.gewu.pm.bean.SalesOrderBean;
import com.gewu.pm.ui.activity.filter.FilterSalesOrderActivity;
import com.gewu.pm.ui.adapter.order.SalesOrderAdapter;
import com.gewu.pm.ui.dialog.CustomTimeDialog;
import com.gewu.pm.ui.popup.SelectTimePopup;
import com.gewu.pm.widget.FilterBar;
import com.hjq.base.BaseAdapter;
import com.hjq.base.BaseDialog;
import com.hjq.base.BasePopupWindow;
import com.hjq.widget.view.EmptyView;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.List;

/**
 * 销售订单页面
 */
public final class SalesOrderActivity extends AppActivity
        implements OnRefreshLoadMoreListener, BaseAdapter.OnItemClickListener {

    private SmartRefreshLayout srlRefresh;
    private RecyclerView rvOrderList;
    private FilterBar filterBar;
    private EmptyView emptyView;
    private TextView tvTotalAmount;
    private TextView btnExport;

    private SalesOrderAdapter adapter;

    /** 销售订单列表 */
    private List<SalesOrderBean> orderList = new ArrayList<>();

    public static void start(Context context) {
        Intent intent = new Intent(context, SalesOrderActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.sales_order_activity;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        srlRefresh = findViewById(R.id.srl_refresh);
        rvOrderList = findViewById(R.id.rv_order_list);
        filterBar = findViewById(R.id.filter_bar);
        emptyView = findViewById(R.id.empty_view);
        tvTotalAmount = findViewById(R.id.tv_total_amount);
        btnExport = findViewById(R.id.btn_export);

        // 设置适配器
        adapter = new SalesOrderAdapter(this);
        adapter.setOnItemClickListener(this);
        rvOrderList.setAdapter(adapter);

        // 设置刷新监听
        srlRefresh.setOnRefreshLoadMoreListener(this);

        // 设置 FilterBar 点击事件
        setOnClickListener(filterBar.getDateFilterLayout(), btnExport);
    }

    @Override
    protected void initData() {
        orderList = new ArrayList<>();
        // 设置默认时间筛选为"最近30天"
        filterBar.setDateFilterText("最近30天");

        // 加载模拟数据
        loadMockData();
    }

    @Override
    public void onRightClick(View view) {
        super.onRightClick(view);
        //FilterSalesActivity.start(getActivity());
        FilterSalesOrderActivity.start(this);
    }

    @SingleClick
    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view == filterBar.getDateFilterLayout()) {
            // 时间筛选点击
            List<String> timeOptions = new ArrayList<>();
            timeOptions.add("今天");
            timeOptions.add("昨天");
            timeOptions.add("本月");
            timeOptions.add("上月");
            timeOptions.add("最近7天");
            timeOptions.add("最近30天");
            timeOptions.add("自定义时间");

            String currentText = filterBar.getDateFilterTextView().getText().toString();

            new SelectTimePopup.Builder(getContext())
                    .setList(timeOptions)
                    .setSelectedItem(currentText)  // 根据当前显示的文本设置选中项
                    .setListener(new SelectTimePopup.OnListener() {
                        @Override
                        public void onSelected(BasePopupWindow popupWindow, String selectedTime) {
                            if ("自定义时间".equals(selectedTime)) {
                                // 显示自定义时间对话框
                                showCustomTimeDialog();
                            } else {
                                filterBar.setDateFilterText(selectedTime);
                                // TODO: 根据选择的时间筛选数据
                                toast("选择了：" + selectedTime);
                            }
                        }
                    })
                    .showAsDropDown(filterBar.getDateFilterLayout());
        } else if (view == btnExport) {//新增订单
            NewOrderActivity.start(getActivity());
        }
    }

    /**
     * 显示自定义时间对话框
     */
    private void showCustomTimeDialog() {
        new CustomTimeDialog.Builder(getContext())
                .setListener(new CustomTimeDialog.OnListener() {
                    @Override
                    public void onSelected(BaseDialog dialog, int startYear, int startMonth, int startDay,
                                           int endYear, int endMonth, int endDay) {
                        // 格式化日期显示
                        String startDate = startYear + "-" + String.format("%02d", startMonth) + "-" + String.format("%02d", startDay);
                        String endDate = endYear + "-" + String.format("%02d", endMonth) + "-" + String.format("%02d", endDay);
                        String timeRange = startDate + " 至 " + endDate;

                        // 更新 FilterBar 显示的日期文本
                        filterBar.setDateFilterText(timeRange);
                        toast("自定义时间：" + timeRange);
                        // TODO: 根据自定义时间筛选数据
                    }
                })
                .show();
    }

    /**
     * 加载模拟数据
     */
    private void loadMockData() {
        orderList.clear();

        // 生成6条数据，对应6种状态
        orderList.add(new SalesOrderBean(
                "杭州配送站点A",
                "张三",
                "2025-08-18 10:30",
                "SO202508180001",
                "V001",
                "顺丰速运",
                "王业务",
                "华东区",
                "¥1200.00",
                "1" // 已审批
        ));

        orderList.add(new SalesOrderBean(
                "上海配送中心B",
                "李四",
                "2025-08-18 11:00",
                "SO202508180002",
                "V002",
                "圆通快递",
                "李销售",
                "华东区",
                "¥2500.00",
                "2" // 部分发货
        ));

        orderList.add(new SalesOrderBean(
                "北京销售点C",
                "王五",
                "2025-08-18 14:20",
                "SO202508180003",
                "V003",
                "申通快递",
                "张经理",
                "华北区",
                "¥800.00",
                "3" // 未审批
        ));

        orderList.add(new SalesOrderBean(
                "深圳配送站D",
                "赵六",
                "2025-08-18 15:45",
                "SO202508180004",
                "V004",
                "中通快递",
                "刘专员",
                "华南区",
                "¥3200.00",
                "4" // 已发货
        ));

        orderList.add(new SalesOrderBean(
                "广州终端E",
                "钱七",
                "2025-08-18 16:30",
                "SO202508180005",
                "V005",
                "韵达快递",
                "陈主管",
                "华南区",
                "¥1500.00",
                "5" // 已完成
        ));

        orderList.add(new SalesOrderBean(
                "成都销售点F",
                "孙八",
                "2025-08-18 17:00",
                "SO202508180006",
                "V006",
                "德邦物流",
                "赵顾问",
                "西南区",
                "¥600.00",
                "6" // 已取消
        ));

        adapter.setData(orderList);

        // 计算总金额
        calculateTotalAmount();

        // 更新空视图状态
        updateEmptyView();
    }

    /**
     * 计算订单总额
     */
    private void calculateTotalAmount() {
        double total = 0;
        for (SalesOrderBean order : orderList) {
            String amount = order.getAmount().replace("¥", "").replace(",", "");
            try {
                total += Double.parseDouble(amount);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        tvTotalAmount.setText(String.format("¥%.2f", total));
    }

    /**
     * 更新空视图状态
     */
    private void updateEmptyView() {
        if (orderList.isEmpty()) {
            emptyView.setVisibility(View.VISIBLE);
        } else {
            emptyView.setVisibility(View.GONE);
        }
    }

    /**
     * {@link OnRefreshLoadMoreListener}
     * 下拉刷新
     */
    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        // 模拟刷新
        postDelayed(() -> {
            loadMockData();
            srlRefresh.finishRefresh();
            toast("刷新成功");
        }, 1000);
    }

    /**
     * {@link OnRefreshLoadMoreListener}
     * 上拉加载
     */
    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        // 模拟加载更多
        postDelayed(() -> {
            srlRefresh.finishLoadMore();
            toast("暂无更多数据");
        }, 1000);
    }

    /**
     * {@link BaseAdapter.OnItemClickListener}
     * 列表项点击
     */
    @Override
    public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
        SalesOrderBean order = adapter.getItem(position);
        // 跳转到销售订单详情页面
        SalesOrderDetailsActivity.start(this, order.getStatus(), order.getTerminalName());
    }
}

